#!/bin/bash

set -e # Exit immediately if a command exits with a non-zero status.
set -u # Treat unset variables as an error.

# Load mandatory environment variables.
source hooks/load_vars

# Load Docker build arguments.
if [ ! -f versions/"$BASEIMAGE_DOCKER_TAG" ]; then
    echo "ERROR: Invalid BASEIMAGE_DOCKER_TAG"
    exit 1
fi
source versions/"$BASEIMAGE_DOCKER_TAG"

if [ "${USE_DOCKER_BUILD_CACHE:-0}" -eq 1 ]; then
    DOCKER_BUILD_CACHE_OPTS=
else
    DOCKER_BUILD_CACHE_OPTS="--no-cache --pull"
fi

echo "$(basename "$0") hook environment variables:"
( set -o posix ; set | sort | sed 's/^/    /')

echo "Starting build of Docker image $BASEIMAGE_DOCKER_IMAGE_NAME..."
docker build $DOCKER_BUILD_CACHE_OPTS \
             --build-arg BASEIMAGE="$BASEIMAGE" \
             --build-arg IMAGE_VERSION="$BASEIMAGE_DOCKER_IMAGE_VERSION" \
             -f "$DOCKERFILE" \
             -t "$BASEIMAGE_DOCKER_IMAGE_NAME" .
